<template>
  <div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
        <!-- 高级查询 -->
        <!-- <super-query :config="superQueryConfig" @search="handleSuperQuery" /> -->
        <a-button type="primary" preIcon="ant-design:export-outlined" @click="handleCustomExport"> 导出</a-button>
        <Button type="primary" @click="handleSuperSearch">高级查询</Button>
      </template>

      <template #img="{ text }">
        <!-- <img :src="text" alt="" /> -->
        <TableImg v-if="text" :size="50" :simpleShow="true" :imgList="[text]" style="object-fit: cover; width: 50px; height: 50px" />
        <TableImg v-else :size="50" :simpleShow="true" :imgList="[placeholderImage]" style="object-fit: cover; width: 50px; height: 50px" />
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template>
    </BasicTable>

    <!-- 表单区域 -->
    <GoodsDetail v-if="showModal" @register="registerModal" />
    <CustomQuery :title="'高级查询'" :height="500" @register="registerSearchModal" @handle-submit="handleSearchSubmit" @handle-close="handleClose" />
  </div>
</template>

<script lang="ts" name="goods-goods" setup>
  import { ref, reactive, h, nextTick } from 'vue';
  import { BasicTable, TableAction, TableImg } from '/@/components/Table';
  import { Button, Modal, Checkbox } from 'ant-design-vue';
  import { useModal } from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage';
  import {
    columns,
    searchFormSchema,
    superQuerySchema,
    formSchema,
    formSchema02,
    formSchema03,
    formSchema04,
    formSchema05,
    formSchema06,
  } from './GoodsSearch.data';
  import { list, handleExportByFields } from './GoodsSearch.api';
  import { useRouter } from 'vue-router';

  import placeholderImage from '/@/assets/images/placeholderImage.png';

  import GoodsDetail from './GoodsDetail.vue';
  import CustomQuery from './components/CustomQuery.vue';
  let router = useRouter();
  const showModal = ref(true);
  const modalAction = ref(''); // 记录当前操作类型
  //导出字段集合
  const exportFields = ref<{ value: string; label: string }[]>([
    { value: 'goodsCode', label: '产品编码' },
    { value: 'goodsName', label: '产品中文名' },
  ]);
  // 是否导出图片
  const includeImages = ref(false);
  const queryParam = reactive<any>({});
  // 高级查询配置
  const superQueryConfig = reactive(superQuerySchema);
  //注册model
  const [registerModal, { openModal }] = useModal();
  const [registerSearchModal, { openModal: openSearchModal }] = useModal();
  //注册table数据
  const { tableContext } = useListPage({
    tableProps: {
      title: '产品信息',
      api: list,
      columns,
      canResize: false,
      formConfig: {
        labelWidth: 120,
        schemas: searchFormSchema,
        autoSubmitOnEnter: true,
        showAdvancedButton: true,
        fieldMapToTime: [['careateTime', ['careateStartTime', 'careateEndTime'], 'YYYY-MM-DD HH:mm:ss']],
      },
      actionColumn: {
        width: 160,
        title: '操作',
        dataIndex: 'action',
        slots: { customRender: 'action' },
        fixed: 'right',
      },
    },
  });

  const [registerTable, { reload, getForm }, { rowSelection, selectedRowKeys }] = tableContext;

  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        label: '详情',
        onClick: handleDetail.bind(null, record),
      },
    ];
  }
  /**
   * 详情
   */
  function handleDetail(record: Recordable) {
    modalAction.value = 'detail';
    showModal.value = false;
    nextTick(() => {
      showModal.value = true;
      nextTick(() => {
        openModal(true, {
          record,
          isUpdate: true,
          showFooter: false,
        });
      });
    });
  }
  /**
   * 导出
   */
  function handleCustomExport() {
    Modal.confirm({
      title: '导出设置',
      content: createFieldSelectionContent(),
      okText: '确认导出',
      cancelText: '取消',
      onOk: () => {
        if (!exportFields.value || exportFields.value.length === 0) {
          Modal.warning({ title: '提示', content: '请至少选择一个导出字段' });
          return Promise.reject('未选择导出字段');
        }

        const formValues = getForm().getFieldsValue();
        console.log('查询form的数据', formValues);
        const queryParam = { ...formValues };
        const bodyParams = {
          fields: exportFields.value.map((item) => item.value), // 提取value
          fieldTitles: exportFields.value.map((item) => item.label), // 提取label
          selectedIds: selectedRowKeys.value.length > 0 ? selectedRowKeys.value : undefined,
          includeImages: includeImages.value,
        };

        return handleExportByFields('商品导出', queryParam, bodyParams);
      },
    });
  }

  function createFieldSelectionContent() {
    const formSchemas = [
      { name: '基础信息', schema: formSchema },
      { name: '产品价格', schema: formSchema02 },
      { name: '电商平台销售价格', schema: formSchema03 },
      { name: '产品英文资料', schema: formSchema04 },
      { name: '产品发货', schema: formSchema05 },
      { name: '产品图片', schema: formSchema06 },
    ];

    // 每次都重置为默认选项，而不是使用上次的选择
    const checkedState = ref({
      fields: ['goodsCode', 'goodsName'], // 默认选中项
      includeImages: false, // 默认不导出图片
    });

    // 同时重置全局状态
    exportFields.value = [
      { value: 'goodsCode', label: '产品编码' },
      { value: 'goodsName', label: '产品中文名' },
    ];
    includeImages.value = false;

    //使用响应式引用存储选中状态
    // const checkedState = ref({
    //   fields: exportFields.value.map((item) => item.value),
    //   includeImages: includeImages.value,
    // });

    const updateFieldSelection = (fieldValue, fieldName, checked) => {
      if (checked) {
        if (!checkedState.value.fields.includes(fieldValue)) {
          checkedState.value.fields.push(fieldValue);
        }
      } else {
        checkedState.value.fields = checkedState.value.fields.filter((f) => f !== fieldValue);
      }

      // 同步到全局状态并去重
      const uniqueFields = [...new Set(checkedState.value.fields)];
      checkedState.value.fields = uniqueFields;

      exportFields.value = formSchemas
        .flatMap((group) => group.schema.filter((col) => uniqueFields.includes(col.field)).map((col) => ({ value: col.field, label: col.label })))
        .filter((item, index, self) => index === self.findIndex((t) => t.value === item.value));
    };

    const updateImageSelection = (checked) => {
      checkedState.value.includeImages = checked;
      includeImages.value = checked;
    };

    const treeNodes = formSchemas.map((formGroup) => {
      const fields = formGroup.schema.filter((col) => {
        if (formGroup.name !== '基础信息') {
          return col.field && col.label && col.field !== 'goodsCode';
        }
        return col.field && col.label;
      });

      const groupFields = fields.map((field) => ({
        ...field,
        checked: checkedState.value.fields.includes(field.field),
      }));

      const allSelected = fields.length > 0 && fields.every((field) => checkedState.value.fields.includes(field.field));
      const someSelected = !allSelected && fields.some((field) => checkedState.value.fields.includes(field.field));

      const checkboxes = groupFields.map((field) =>
        h('div', { style: { margin: '8px 0', paddingLeft: '20px' } }, [
          h('label', { style: { display: 'flex', alignItems: 'center' } }, [
            h('input', {
              type: 'checkbox',
              checked: field.checked,
              onChange: (e) => {
                updateFieldSelection(field.field, field.label, e.target.checked);
              },
              style: { marginRight: '8px' },
            }),
            h('span', field.label),
          ]),
        ])
      );

      const selectAllCheckbox = h('div', { style: { margin: '8px 0' } }, [
        h('label', { style: { display: 'flex', alignItems: 'center' } }, [
          h('input', {
            type: 'checkbox',
            checked: allSelected,
            indeterminate: someSelected ? 'indeterminate' : undefined,
            onChange: (e) => {
              const checked = e.target.checked;
              if (checked) {
                fields.forEach((field) => {
                  if (!checkedState.value.fields.includes(field.field)) {
                    updateFieldSelection(field.field, field.label, true);
                  }
                });
              } else {
                fields.forEach((field) => {
                  updateFieldSelection(field.field, field.label, false);
                });
              }
            },
            style: { marginRight: '8px' },
          }),
          h('span', '全选'),
        ]),
      ]);

      const groupHeader = h(
        'div',
        {
          style: {
            fontWeight: 'bold',
            borderBottom: '1px solid #eee',
            paddingBottom: '5px',
            marginBottom: '5px',
            marginTop: '10px',
          },
        },
        formGroup.name
      );

      return h('div', [groupHeader, selectAllCheckbox, ...checkboxes]);
    });

    const imageExportOption = h('div', { style: { margin: '15px 0 8px', padding: '10px 0', borderTop: '1px solid #f0f0f0' } }, [
      h('strong', '导出选项'),
      h('div', { style: { margin: '8px 0' } }, [
        h('label', { style: { display: 'flex', alignItems: 'center' } }, [
          h('input', {
            type: 'checkbox',
            checked: checkedState.value.includeImages,
            onChange: (e) => {
              updateImageSelection(e.target.checked);
            },
            style: { marginRight: '8px' },
          }),
          h('span', '是否导出图片（封面图）'),
        ]),
      ]),
    ]);

    // 获取去重后的选中标签
    const selectedLabels = formSchemas
      .flatMap((group) => group.schema.filter((col) => checkedState.value.fields.includes(col.field)).map((col) => col.label))
      .filter((label, index, self) => self.indexOf(label) === index);

    const scrollableCheckboxContainer = h(
      'div',
      {
        style: {
          maxHeight: '400px',
          overflowY: 'auto',
          paddingRight: '10px',
          border: '1px solid #f0f0f0',
          borderRadius: '4px',
          padding: '10px',
          marginTop: '10px',
        },
      },
      [...treeNodes]
    );

    return h('div', [h('p', `已选字段: ${selectedLabels.join(', ')}`), scrollableCheckboxContainer, imageExportOption]);
  }
  /**
   * 高级查询
   */
  function handleSuperSearch() {
    openSearchModal(true, {
      height: 500,
    });
  }
  /** 高级查询提交事件 */
  function handleSearchSubmit(arr) {
    arr.forEach((item) => {
      let value = JSON.parse(JSON.stringify(item.linkValue));
      if (typeof value !== 'string') {
        value = `${value}`;
      }
      if (item.linkCondition !== '=') {
        queryParam[`${item.linkKey}_${item.linkCondition}`] = value;
      } else {
        queryParam[item.linkKey] = value;
      }
    });
    console.log(queryParam, 'queryParam');
    debugger;
    if (typeof reload === 'function') {
      reload({ searchInfo: queryParam });
      // handleClose();
    }
  }
  /** 关闭高级查询弹窗 */
  function handleClose() {
    openSearchModal(false);
  }
</script>
<style scoped>
  .text-two-lines {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    word-break: break-all;
    word-wrap: break-word;
    line-height: 1.5;
    text-align: left;
  }
</style>
